package com.szp.drug.component.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szp.drug.component.mapper.DrugRoleMapper;
import com.szp.drug.component.service.api.DrugRoleService;
import com.szp.drug.entity.DrugRole;
import com.szp.drug.util.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 角色实现类
 * @author SuZePing
 * @create 2021-01-19 8:10
 * @E-mail suzeping10@126.com
 */
@Slf4j
@Service
public class DrugRoleServiceImpl extends ServiceImpl<DrugRoleMapper, DrugRole> implements DrugRoleService {

	@Autowired
	private DrugRoleMapper roleMapper;

	/**
	 * 分页获取role
	 * @param keyword
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Override
	public ResultEntity<PageInfo<DrugRole>> getPageInfo(String keyword, String pageNum, String pageSize) {
		// 开启分页
		PageHelper.startPage(Integer.parseInt(pageNum),Integer.parseInt(pageSize));
		QueryWrapper<DrugRole> wrapper = new QueryWrapper<>();
		wrapper.like("role_name",keyword).orderByAsc("role_id");
		List<DrugRole> roles = roleMapper.selectList(wrapper);
		return ResultEntity.success(new PageInfo<>(roles));
	}

	/**
	 * 新增role(并返回新增后总数量)
	 * @param role
	 * @return
	 */
	@Override
	public ResultEntity<Integer> saveRole(DrugRole role) {
		QueryWrapper<DrugRole> wrapper = new QueryWrapper<>();
		wrapper.eq("role_name",role.getRoleName());
		List<DrugRole> selRoles = roleMapper.selectList(wrapper);
		if (selRoles.size() != 0){
			return ResultEntity.error("角色名重复！");
		}
		roleMapper.insert(role);
		// 返回新增后总数量 为数据展示页码使用
		List<DrugRole> roles = roleMapper.selectList(Wrappers.emptyWrapper());
		return ResultEntity.success(roles.size());
	}

	/**
	 * 修改role
	 * @param role
	 * @return
	 */
	@Override
	public ResultEntity<String> editRole(DrugRole role) {
		String roleId = role.getRoleId();
		String roleName = role.getRoleName();
		QueryWrapper<DrugRole> wrapper = new QueryWrapper<>();
		wrapper.eq("role_name",roleName);
		List<DrugRole> selRoles = roleMapper.selectList(wrapper);
		// 修改时可以使角色名修改为当前角色名
		if (selRoles.size() != 0 && !Objects.equals(roleId,selRoles.get(0).getRoleId())){
			return ResultEntity.error("角色名重复！");
		}
		roleMapper.updateById(role);
		return ResultEntity.success();
	}

	/**
	 * 删除role
	 * @param roleIds
	 * @return
	 */
	@Override
	public ResultEntity<String> removeRole(List<String> roleIds) {
		UpdateWrapper<DrugRole> wrapper = new UpdateWrapper<>();
		wrapper.in("role_id",roleIds);
		roleMapper.delete(wrapper);
		return ResultEntity.success();
	}

}
